package per.srp.demo.carLink.log;

import per.srp.demo.carLink.Utils.TimeFormat;

import java.io.*;
import java.net.Socket;

public class CarLogger {
    private static int times = 0;
    private static int[] timesArray={
            1,2,3,4,5,6,7,8,9,10,
            11,12,13,14,15,16,17,18,19,0,
            0,0,0
    };
    private static int frequency = 4;

    private static String logBaseDir="./";
    private static String filename="carLinkLog";

    synchronized private static void write(LogType type,String msg) throws IOException {
        String fileTime = TimeFormat.formatTimeString("yyyy-MM-dd");
        String time = TimeFormat.formatTimeString("HH:mm:ss");
        File f = new File(logBaseDir+"/"+filename+"-"+fileTime+".log");
        if(!f.isFile()){
            f.createNewFile();
        }
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(f, true));
        out.write(time+" ["+type.getName()+"] "+msg+"\n");
        out.flush();
        out.close();
    }

    public static void log(LogType type,String msg) throws IOException {

        //利用times，减少记录数量，防止日志过多
        if(times<frequency){
            write(type,msg);
        }
        times = timesArray[times];
    }

    public static void log(LogType type, Socket socket, String msg) throws IOException {
        //利用times，减少记录数量，防止日志过多
        if(times<frequency){
            write(type,socket.getInetAddress()+":"+socket.getPort()+" "+msg);
        }
        times = timesArray[times];
    }
}
